package com.vandzi.android.androidcode;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.TextView;

import com.vandzi.android.androidcode.model.Application;
import com.vandzi.android.androidcode.model.ApplicationsComparator;
import com.vandzi.android.androidcode.service.ActivitiesBringe;
import com.vandzi.android.androidcode.service.AndroidCodeService;
import com.vandzi.android.androidcode.service.InstalledApplicationsService;

public class ApplicationsListActivity extends ListActivity {

	private static final String TAG = "ApplicationsListActivity";

	private ArrayList<Application> applicationsList;
	private ApplicationsAdapter adapter;
	private ProgressDialog progressDialog;

	private RadioButton radioButtonNewest;
	private RadioButton radioButtonMostPopular;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.applications_list);

		loadApplications();

		// Button reload = (Button) findViewById(R.id.buttonReloadApps);
		// reload.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// loadApplications();
		//
		// }
		// });

		radioButtonNewest = (RadioButton) findViewById(R.id.radioButtonNewest);
		radioButtonNewest.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				sort(ApplicationsComparator.SORT_NEWEST);
			}
		});
		radioButtonMostPopular = (RadioButton) findViewById(R.id.radioButtonMostPopular);
		radioButtonMostPopular.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				sort(ApplicationsComparator.SORT_MOST_POPULAR);
			}
		});
	}

	/**
	 * sort applications list and notify to refresh view
	 * 
	 * @param condition
	 *            - ApplicationsComparator.SORT_*
	 */
	private void sort(int condition) {
		adapter.sort(new ApplicationsComparator(condition));
		adapter.notifyDataSetChanged();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.applications_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.refresh:
			loadApplications();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		itemSelectedAction(position);

	}

	/**
	 * Perform this action when item in list is selected
	 * 
	 * @param position
	 */
	private void itemSelectedAction(int position) {
		Intent appdetails = new Intent(ApplicationsListActivity.this,
				ApplicationDetailsActivity.class);
		// get object from position and pass it to Detail activity
		ActivitiesBringe.setObject(adapter.getItem(position));

		startActivity(appdetails);
	}

	/**
	 * Display progress bar and load applications
	 */
	private void loadApplications() {

		applicationsList = new ArrayList<Application>();
		this.adapter = new ApplicationsAdapter(this, R.layout.application_item,
				applicationsList);
		setListAdapter(this.adapter);

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				getApplications();
			}
		});
		thread.start();
		progressDialog = ProgressDialog.show(ApplicationsListActivity.this, "",
				getText(R.string.progress_loadingapps));
	}

	private class ApplicationsAdapter extends ArrayAdapter<Application> {

		public ApplicationsAdapter(Context context, int textViewResourceId,
				ArrayList<Application> items) {
			super(context, textViewResourceId, items);
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.application_item, null);
				view.setClickable(true);
			}
			Application app = (Application) getItem(position);
			if (app != null) {
				ImageView icon = (ImageView) view
						.findViewById(R.id.imageViewAppIcon);

				TextView name = (TextView) view
						.findViewById(R.id.textViewAppName);
				TextView author = (TextView) view
						.findViewById(R.id.textViewAppAuthorName);
				RatingBar rating = (RatingBar) view
						.findViewById(R.id.ratingBarAppRating);
				TextView applicationInstalled = (TextView) view
						.findViewById(R.id.textViewApplicationInstalled);

				icon.setImageDrawable(app.getImage());
				name.setText(app.getName());
				author.setText(app.getAuthor());
				rating.setRating(app.getAverageRating());

				if (InstalledApplicationsService.isApplicationInstalled(
						app.getPackageName(), getPackageManager())) {
					applicationInstalled
							.setText(getText(R.string.application_installed));
				} else {
					applicationInstalled.setText("");
				}

				rating.setTag(new Integer(position));

				view.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						itemSelectedAction(position);

					}
				});

			}
			return view;
		}

	}

	private Runnable returnRes = new Runnable() {

		@Override
		public void run() {
			if (applicationsList != null && applicationsList.size() > 0) {
				adapter.notifyDataSetChanged();
				for (int i = 0; i < applicationsList.size(); i++)
					adapter.add(applicationsList.get(i));
			}
			progressDialog.dismiss();
			adapter.notifyDataSetChanged();
			radioButtonNewest.setChecked(true);

		}
	};

	private void getApplications() {

		try {
			ArrayList<Application> applications = new ArrayList<Application>();

			int i = 0;
			// because of connection problems, repeat it automatically few times
			while (applications.size() <= 0 && i < 10) {
				i++;
				applications = AndroidCodeService.parseApplications();
				// Log.e(TAG, String.valueOf(i));
			}

			applicationsList = applications;
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}

		runOnUiThread(returnRes);
	}
}
